<template>
  <div class="box">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-menu"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="handle-box">
      <el-form ref="serch" :model="serch" :inline="true">
        <el-form-item>
          <el-input v-model="serch.username" size="small" placeholder="输入姓名检索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="small" @click="doSearch" plain round>搜索</el-button>
          <el-button type="primary" @click="initAdd" class="handle-del mr10" :disabled="userPermission!==1" size="small" round icon="el-icon-plus"
                     plain>添加用户
          </el-button>
        </el-form-item>
      </el-form>

    </div>
    <el-table :data="page.list" stripe :height=500 style="width: 100%">
      <el-table-column prop="username" header-align="center" label="姓名" width="120">
      </el-table-column>
      <el-table-column prop="usernum" header-align="center" label="账号" width="120">
      </el-table-column>
      <el-table-column prop="role" header-align="center" label="是否管理员">
        <template scope="scope">
          <el-tag v-if="scope.row.role===1">管理员</el-tag>
          <el-tag type="danger" v-if="scope.row.role===0">普通用户</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deleted" header-align="center" label="用户状态">
        <template scope="scope">
          <el-tag type="success" v-if="scope.row.deleted===0">启用</el-tag>
          <el-tag type="danger" v-if="scope.row.deleted===1">删除</el-tag>
          <el-tag type="danger" v-if="scope.row.deleted===2">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="odr" header-align="center" label="排序">
      </el-table-column>
      <el-table-column label="操作" header-align="center" width="400">
        <template scope="scope">
          <el-button size="small" type="primary" icon="el-icon-edit" round plain
                     @click="handleEdit(scope.$index, scope.row)" :disabled="userPermission!==1">编辑
          </el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" :disabled="scope.row.deleted === true || userPermission!==1"
                     @click="handleDelete(scope.$index, scope.row)" round plain>删除
          </el-button>
          <el-button size="small" type="warning" icon="el-icon-refresh" @click="restPassword(scope.$index, scope.row)"
                     :disabled="userPermission!==1" round plain>密码重置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="page.pageNum"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes:="[10, 20, 30,40, 50,100]"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog width="30%" title="编辑用户信息" :before-close="dailogClose" :visible.sync="addUserVisible" center>
      <el-form :model="user" :rules="userRules" ref="user" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="usernum">
          <el-input v-model="user.usernum"></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-radio class="radio" v-model="user.role" :label="1">管理员</el-radio>
          <el-radio class="radio" v-model="user.role" :label="0">普通用户</el-radio>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio class="radio" v-model="user.deleted" :label="0">启用</el-radio>
          <el-radio class="radio" v-model="user.deleted" :label="2">禁用</el-radio>
        </el-form-item>
        <!--<span style="float:right;color: red">* 新用户密码默认为hdrs123456</span>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import common from '../../../common/constant.js'
  import ElFormItem from '../../../../node_modules/element-ui/packages/form/src/form-item'
  import {Loading} from 'element-ui'
  export default {
    data() {
      const current = 1
      return {
        userList: [],
        userRole: 0,
        multipleSelection: [],
        select_cate: '',
        select_word: '',
        page: {
          pageNum: 1,
          pageSize: 10,
          size: 2,
          orderBy: null,
          startRow: 3,
          endRow: 4,
          total: 4,
          pages: 2,
          list: [],
          firstPage: 1,
          prePage: 1,
          nextPage: 0,
          lastPage: 2,
          isFirstPage: false,
          isLastPage: true,
          hasPreviousPage: true,
          hasNextPage: false,
          navigatePages: 8,
          navigatepageNums: [
            1,
            2
          ]
        },
        user: {
          id: null,
          username: '',
          usernum: '',
          odr: 1,
          role: 0,
          deleted: 0
        },
        userRules: {
          username: [
            {required: true, message: '请输入用户姓名', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
          ],
          usernum: [
            {required: true, message: '请输入用户编号', trigger: 'blur'},
            {min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur'}
          ]
        },
        serch: {
          username: null
        },
        addUserVisible: false,
        confirm: false,
        allowConfirm: false,
        restPWDonfirm: false,
        row: [] // 保存一行数据
      }
    },
    computed: {
      userPermission(){
        let user = JSON.parse(sessionStorage.getItem('user'))
        return user.role
      }
    },
    created(){
      this.query();
    },
    methods: {
      handleSizeChange(value){
        this.page.pageSize = value
        this.query()
      },
      handleCurrentChange(val) {
        let self = this
        self.page.currentPage = val
        self.query()
      },
      dailogClose(){
        this.addUserVisible = false
        this.$refs['user'].resetFields()
        this.user = {
          id: null,
          username: '',
          usernum: '',
          odr: 1,
          role: 0,
          deleted: 0
        }
      },
      doSearch(){
        this.query()
      },
      query(){
        let self = this;
        self.$http.post('/api/user', {
          'pageSize': self.page.pageSize,
          'pageNum': self.page.pageNum,
          username: self.serch.username
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.page = responseData.pageData
            } else {
              self.message_error('查询用户列表错误！^_^;')
            }
          })
          .catch(function (response) {
            self.message_error('查询用户列表异常！^_^;')
          })
      },
      queryOne(id){
        let self = this;
        self.$http.post('/api/user', {
          'id': id,
          'pageSize': self.page.pageSize,
          'pageNum': self.currentPageNum
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.user = responseData.pageData.list[0]
              console.log(self.user)
            } else {
              self.message_error('查询用户列表错误！^_^;')
            }
          })
          .catch(function (response) {
            self.message_error('查询用户列表异常！^_^;')
          })
      },
      submitUser() {
        let self = this;
        self.$refs['user'].validate((valid) => {
          if (valid) {
            let loadingInstance = Loading.service({
              fullscreen: true,
              text: "提交中......"
            })
            self.$http.post('/api/user/save', self.user)
              .then((response) => {
                let responseData = response.data
                if (responseData.flag === common.respons.seccuss) {
                  self.addUserVisible = false
                  self.message_ok('保存用户成功！^_^')
                  self.query()
                } else {
                  self.message_error('保存用户失败!^_^;')
                }
                loadingInstance.close()
              })
              .catch(function (response) {
                loadingInstance.close()
                self.message_error('保存用户异常!^_^;')
              })
          } else {
            return false
          }
        })
      },
      /**
       *弹出添加用户页面
       */
      initAdd(){
        let self = this
        self.addUserVisible = true
      },
      roleFormatter(row, column) {
        if (row.role === true) {
          return '管理员'
        }
        return '普通用户';
      },
      filterTag(value, row) {
        return row.tag === value;
      },
      handleEdit(index, row) {
        let self = this
        self.addUserVisible = true
        self.queryOne(row.id)
      },
      handleDelete(index, row) {
        let self = this
        self.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$http.post('/api/user/save', {
            id: row.id,
            deleted: common.recordStatus.deleted
          })
            .then((response) => {
              let responseData = response.data
              if (responseData.flag === common.respons.seccuss) {
                self.query()
                self.message_ok('删除用户成功鸟！^_^')
              } else {
                self.message_error('删除用户失败！^_^;')
              }
            })
            .catch(function (response) {
              self.message_error('删除用户异常！^_^;')
            })
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '已取消删除'
          })
        })
      },
      /**
       * 打开重置密码提示框
       * */
      restPassword(index, row){
        let self = this
        self.$confirm('此操作将有可能导致用户无法登录, 是否继续重置【 ' + row.username + '】的密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(() => {
          self.$http.get('/api/user/reset/' + row.id)
            .then((response) => {
              let responseData = response.data
              if (responseData.flag === common.respons.seccuss) {
                self.query()
                self.message_ok('重置用户密码成功鸟！^_^')
              } else {
                self.message_error('重置用户密码失败！^_^;')
              }
            })
            .catch(function (response) {
              self.message_error('重置用户密码异常！^_^;')
            })
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '已取消重置用户密码'
          })
        })
      },
      restUserPwd(){
        let self = this
        self.$http.get('/api/user/reset/' + self.row.userId)
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.addUserVisible = false
              self.message_ok('操作成功')
              self.initData()
            } else {
              self.message_error('操作失败')
            }
          })
          .catch(function (response) {
            self.message_error()
          })
        self.restPWDonfirm = false
      },
      /**
       * 启用/禁用
       * @param deleted
       */
      confirmHandle(deleted){
        let self = this
        self.user = self.row
        self.user.deleted = deleted
        self.submitUser()
        self.confirm = false
        self.allowConfirm = false
      },
      handleSelectionChange: function (val) {
        this.multipleSelection = val;
      },
      message_error(message) {
        if (message === null) {
          this.$notify.error({
            title: '错误',
            message: '操作失败'
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: message
          });
        }
      },
      message_ok(message) {
        if (message === null) {
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success'
          });
        } else {
          this.$notify({
            title: '成功',
            message: message,
            type: 'success'
          });
        }

      }
    }
  }
</script>

<style scoped>

</style>
